<template>
  <div>
    <div class = "card" style="margin-bottom: 5px;">
      <el-input style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入名称查询" prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="warning" @click="reset">重 置</el-button>
    </div>
    <div class = "card" style="margin-bottom: 5px">
      <el-button v-if="data.user.role === 'owner'" type="primary" @click="handleadd">添 加</el-button>
      <el-button type="danger" @click="deleteBatch">批 量 删 除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" border stripe string @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="序号" prop = "id"/>
        <el-table-column label="房间图片" prop = "roomImages">
          <template #default="scope">
            <template v-if="scope.row.roomImages.length > 0">
              <img v-for="(image,index) in scope.row.roomImages" :key="index" :src="image" alt="房间图片" style="width: 40px;height: 40px;display:inline-block;border-radius: 50%">
            </template>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="房间所属分类" prop = "roomType"/>
        <el-table-column label="房间名称" prop = "name"/>
        <el-table-column label="介绍" prop = "description" show-overflow-tooltip/>
        <el-table-column label="价格/月" prop = "price"/>
        <el-table-column label="房东电话" prop = "owner.phone"/>
        <el-table-column label="房东姓名" prop = "owner.name"/>
        <el-table-column label="状态" prop = "status">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'danger' : 'success'">
              {{ scope.row.status === '1' ? '已下架' : '可出租' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" :icon="Edit"   :disabled="scope.row.status === '1'" circle @click="handleUpdate(scope.row)"  ></el-button>
            <el-button type="danger"  :icon="Delete"  circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-bottom: 15px">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5,10,15,20]"
            backgroudr
            layout="total, sizes, prev, pager, next,jumper"
            :total="data.total"
        />
      </div>
    </div>
    <el-dialog :title="data.dislog1Title" v-model="data.formVisible1"  width="600">
      <el-form :model="data.form" :rules="data.rules" style="padding-right: 50px;padding-top: 20px">
        <el-form-item label="房间图片" label-width="80px">
          <template v-if="!data.isEditing">
            <el-upload
                class="upload-demo"
                action="http://localhost:9090/file/upload"
                :multiple="true"
                :file-list="fileList"
                list-type="picture-card"
                :on-success="handleSuccessUploadImages"
                :before-upload="beforeUpload"
                :limit="3"
                :on-exceed="handleExceed"
                :headers="{Authorization:uploadToken.token}"
            >
              <el-icon><Plus /></el-icon> <!-- 在编辑模式下不显示添加图片按钮 -->
              <template #tip>
                <div class="el-upload__tip">
                  格式为.jpg/.png,且不超过1mb
                </div>
              </template>
            </el-upload>
          </template>

          <template v-else>
            <template v-if="data.form.roomImages.length > 0">
              <img v-for="(image,index) in data.form.roomImages" :key="index" :src="image" alt="房间图片" style="width: 40px;height: 40px;display:inline-block;border-radius: 50%">
            </template>
            <span v-else>暂无图片</span>
          </template>

        </el-form-item>

        <el-form-item label="房间分类" label-width="80px">
          <el-select v-model="data.form.typeId" placeholder="请选择房间分类" @change="handleRoomTypeChange">
            <el-option
                v-for="type in data.roomTypes"
                :key="type.id"
                :label="type.name"
                :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房间名称" label-width="80px">
          <el-input  v-model="data.form.name"  placeholder="请输入房间名称"autocomplete="off" />
        </el-form-item>

        <el-form-item label="介绍" label-width="80px">
          <el-input  v-model="data.form.description"  placeholder="请输入房间介绍"autocomplete="off" />
        </el-form-item>

        <el-form-item label="价格" label-width="80px">
          <el-input  v-model="data.form.price"  placeholder="请输入房间价格"autocomplete="off" />
        </el-form-item>

        <el-form-item label="状态" label-width="80px">
          <el-select v-model="data.form.status" placeholder="请选择房间状态">
            <el-option label="可出租" value="0"/>
            <el-option label="已下架" value="1"/>
          </el-select>
        </el-form-item>

        <el-form-item label="地区" label-width="80px">
          <el-input  v-model="data.form.area"  placeholder="请输入房间详细地址"autocomplete="off" />
        </el-form-item>

        <el-form-item label="面积" label-width="80px">
          <el-input  v-model="data.form.size"  placeholder="请输入房间面积"autocomplete="off" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible1 = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "../../utils/request.js";
import {Delete,Search,Picture,Edit,ArrowDown} from '@element-plus/icons-vue'
import {ElMessage,ElMessageBox} from "element-plus";
import { reactive,ref } from "vue";
import {useTokenStore} from "../../stores/token";

const data = reactive({
  user:JSON.parse(localStorage.getItem('localStorageUser')),
  name:null,
  tableData:[],
  pageNum:1,
  pageSize:10,
  total:0,
  formVisible1:false,
  dislog1Title:'',
  formVisible2:false,
  ids:[],
  isEditing:false,//是否正在编辑
  roomTypes:[],//存储已存在的房间分类

  form:{
    id:null,
    ownerId:null,
    name:null,
    typeId:null,//选择的房间分类id
    typeName:null,//选择的房间分类名称
    description:null,
    price:null,
    status:null,
    phone:null,
    roomImages:[]
  },
  rules:{
    price:[
      {required:true,message:'请输入房间价格',trigger:'blur'},
      {type:'number',message:'价格必须为数字数字',trigger:'blur'}
    ]
  }
})
// 存储已上传文件的列表，用于展示列表形式
const fileList = ref([])


const uploadToken = useTokenStore();
console.log("上传图片的token:"+uploadToken.token)

const load =()=>{
  request.get('/room/SelectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
    }
  }).then(res=>{
    data.tableData = res.data.list
    data.total = res.data.total
  })
}
load()

//获取房间分类数据
const getRoomTypes = async ()=>{
  try {
    const res = await request.get('/roomType/selectAll');
    if (res.code === '200') {
      data.roomTypes = res.data;

    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error('获取房间分类数据失败');
  }
}
getRoomTypes()

const reset = ()=>{
  data.name = null
  load()
}

// 添加房间类型变化处理函数
const handleRoomTypeChange = (typeId) => {
  const selectedType = data.roomTypes.find(type => type.id === typeId);
  if (selectedType) {
    data.form.typeName = selectedType.name;
  }
}

const handleadd = ()=>{
  data.formVisible1 = true
  data.dislog1Title='添加房间'
  data.form = {}
  data.form.roomImages=[]
  fileList.value=[]
  data.form.ownerId=data.user.id
  data.isEditing = false; // 设置为添加模式
}

const handleUpdate = (row)=>{
  data.dislog1Title='编辑房间'
  data.form = JSON.parse(JSON.stringify(row))//深拷贝一个对象，这样编辑就不会影响行数据
  data.formVisible1 = true
  // 设置选中的房间类型
  data.form.typeId = row.typeId
  data.form.typeName = row.typeName
  data.isEditing = true

}

const handleExceed =(files, fileList)=>{
  ElMessage.error('最多上传3张图片')
}


// 上传前的钩子函数，可在这里进行文件格式等验证（与后端验证配合）
const beforeUpload = (file)=>{

  if (file.type !== 'image/jpeg' && file.type !== 'image/png'){
    ElMessage.error('图片格式不正确，请上传jpg/png格式的图片!')
    return false
  }
  if (file.size / 1024 / 1024 > 1) {
    ElMessage.error('图片大小不能超过 1MB!')
    return false
  }

  return true
}



const handleSuccessUploadImages = (res,file,fileList)=>{
  return new Promise((resolve) => {
    console.log('图片上传成功回调被触发，当前返回数据:', res);
    data.form.roomImages = data.form.roomImages.concat(res.data);
    resolve();
  });
}


const handleSelectionChange = (rows)=>{//返回选中所有的行
  //从选中的行数组里取出username组成一个新的数组ids
  data.ids = rows.map(row=>row.id)
  console.log(data.ids)
}


const save =async ()=> {//根据编辑标志isEditing来进行增加/编辑操作
  if (data.isEditing){
    await update()
  }else {
    await add()
  }
  data.formVisible1 = false
}

const add =async ()=>{
  let formattedRoomImages = [];
  data.form.ownerId = data.user.id
// 将data.form.roomImages中的字符串URL转换为包含{url: xxx}格式的对象数组
  if (data.form.roomImages) {
    formattedRoomImages = data.form.roomImages.map(url => ({url}));
  }
  // 构建符合后端要求的请求体数据
  const requestBody = {
    ...data.form,
    roomImages: formattedRoomImages,
    typeId: data.form.typeId,//确保传递typeId
  };
  request.post('/room/add',requestBody).then(res =>{
    console.log("请求体数据",requestBody); // 打印请求体数据
    if (res.code === '200'){
      ElMessage.success('操作成功')
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })

}

const update = ()=>{
  // 使用对象解构和扩展运算符排除 roomImages
  const { roomImages, ...requestBody } = data.form;

  request.put('/room/update', requestBody).then(res =>{
    if (res.code === '200'){
      ElMessage.success('操作成功')
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const del =(id)=>{
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {type: 'warning'}).then(()=>{

    request.delete('/room/delete', {
      params:{
        id:id
      }
    }).then(res =>{
      if (res.code === '200'){
        ElMessage.success('操作成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}

const deleteBatch = ()=>{
  if (data.ids.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  ElMessageBox.confirm('确定要删除这些用户吗？', '提示', {type: 'warning'}).then(()=>{
    request.delete('/room/deleteBatch', {data:data.ids}).then(res =>{
      if (res.code === '200'){
        ElMessage.success('操作成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}



</script>
<style scoped>
.upload-demo.el-upload-list {
  display: flex;
  flex-wrap: wrap;
}
.upload-demo.el-upload-list__item {
  margin-right: 10px;
  margin-bottom: 10px;
}
.image-container {
  display: flex;
  flex-wrap: wrap;
}
.uploaded-image {
  width: 150px;
  height: 150px;
  margin-right: 10px;
  margin-bottom: 10px;
  object-fit: cover;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>